<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.admin.PendingApproval')"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="portlet">
                <div style="width: 450px;height: 20px" v-if="initInning">
                    <a-spin :spinning="initInning"/>
                </div>
                <div v-else>
                    <div class="tools flex-between"></div>
                    <template v-if="empty">
                        <a-empty image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                            <span slot="description">{{$t('pro.admin.ApprovalEmpty')}}</span>
                        </a-empty>
                    </template>
                    <template v-else>
                        <a-table
                                :pagination="false"
                                :loading="loading"
                                rowKey="campaignsCreativeId"
                                :columns="columns"
                                :dataSource="data"
                                :scroll="{ x: 800 }"
                        >
                            <div slot="userName" slot-scope="text,record"  style="display: inline-block;min-width: 130px">
                                {{record.firstName+record.lastName}}
                                (<router-link :to="{ path: '/admin/users/edit/id/'+ record.userId}">
                                #{{record.userId}}
                            </router-link>)
                            </div>
                            <div slot="campaignsName" slot-scope="text,record" style="display: inline-block;min-width: 130px">
                                {{text}}
                                (<a href="javascript:;" @click="editcreative2(record)"> #{{record.campaignId}} </a>)
                            </div>
                            <div slot="creativeName" slot-scope="text,record" style="display: inline-block;min-width: 130px">
                                {{text}}
                                (<a href="javascript:;" @click="editcreative(record)"> #{{record.campaignsCreativeId}} </a>)
                            </div>
                            <template slot="Preview" slot-scope="text,record">
                                <a-button type="primary" @click="PreviewModel(record)" v-text="$t('pro.admin.ShowPreview')">
                                </a-button>
                            </template>
                            <template slot="action" slot-scope="text">
                                <a-button type="primary" shape="circle" icon="check" style="margin-right: 5px"
                                          @click="handleState(text, NOTACTIVE)"/>

                                <a-button type="primary" shape="circle" icon="close" @click="handleState(text,MISTAKEN)"/>
                            </template>
                        </a-table>
                    </template>
                    <a-pagination
                            v-if="!empty"
                            style="text-align: right;margin-top:1rem;"
                            showSizeChanger
                            showQuickJumper
                            :pageSizeOptions="pageSizeOptions"
                            :pageSize="pagination.size"
                            :total="pagination.total"
                            v-model="pagination.current"
                            @showSizeChange="handleChange"
                            @change="handleChange"
                    />
                    <a-modal
                            width="850px"
                            :title="$t('pro.admin.Creativepreview')"
                            v-model="visiblePreview"
                            @ok="handlePreviewClose"
                            :okText="$t('pro.public.buttonClose')"
                            :cancelText="$t('pro.public.buttonNo')"
                            @cancel="handlePreviewNo"
                    >
                        <a-spin :spinning="spinning">
                            <div v-if="mediaType == 'nativeAd' && isDisp" v-html="nativeHtml()"></div>

                            <iframe
                                    v-if="mediaType != 'nativeAd'"
                                    name="iframe"
                                    :srcdoc="validSrc ? previewContent : ''"
                                    frameborder="0"
                                    width="100%"
                                    height="450px"
                            />
                        </a-spin>
                    </a-modal>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import {getCampaignsCreative,getDetailedDataByPage, setDetailedState} from "@/api/campaigns-creative";
    import {parseTime} from '@/utils/time'
    import {NOTACTIVE, MODERATED, MISTAKEN} from "@/utils/publicStatus"

    export default {
        inject: ["reload"],
        data() {
            return {
                initInning: true,
                tagCustomize: "",
                MODERATED, NOTACTIVE, MISTAKEN,
                visiblePreview: false,
                pagination: {
                    size: 10,
                    current: 1,
                }, //分页器
                pageSizeOptions: [''],  //分页下拉列表
                empty: false,  //判断是否有数据
                loading: true, //页面是否加载
                data: [],
                CampaignId: '',
                creativeId:'',
                mediaType: '',//广告的类型
                soundEnable: false,
                autoPlay: false,
                bannerPreview: {
                    size: "",
                    width: "",
                    height: "",
                    iurl: "",
                    imageSource: "",
                    clickUrl: "",
                    alt: "图片"
                },
                videoPreview: {
                    size: "",
                    width: "",
                    height: "",
                    duration: "",
                    videoSrc: "",
                    type: "",
                    clickUrl: ""
                },
                //原生广告
                nativePreview: {
                    title: '',
                    dataDesc: '',
                    sponsor: '',
                    amxImgSrc: '',
                    minImgsrc: '',
                    clickUrl: '',
                    isShow: false,
                },
                spinning: false, //预览加载
                isDisp: false
            }
        },
        computed: {
            // 判断是否时包含有效的资源(图片||视频...)链接,
            // 以决定是否显示预览效果: iframe.srcdoc
            validSrc() {
                const condition1 = this.mediaType == "banners" && this.bannerPreview.iurl;
                const condition2 = this.mediaType == "bannerVideos" && this.videoPreview.videolib;
                const condition3 = this.bannerPreview.banners ? this.bannerPreview.banners.iurl
                    : this.bannerPreview.bannerVideos ? this.bannerPreview.bannerVideos.videolib : "";
                return condition1 || condition2 || condition3;
            },
            previewContent() {
                if (this.mediaType == "banners") {
                    let template = `<a href="${this.bannerPreview.clickUrl}" target="_blank" style="display:block;margin:0 auto;"><img style="width: 100%;overflow: hidden" src="${this.validSrc}" id="picImg" :alt="${this.bannerPreview.alt}"></a>`;
                    return template;
                }

                if (this.mediaType == "bannerVideos") {
                    let templateVideo =  `<video style="width: 100%;overflow: hidden" ref="Video" id="Video" ${this.soundEnable ? "" : "muted"} ${
                        this.autoPlay ? "autoplay" : ""
                        }  controls="controls" style="margin:0 auto;">
                        <source src="${this.validSrc}" type="video/${
                        this.validSrc.split(".")[this.validSrc.split(".").length - 1]
                        }" v-text="$t('pro.EditCreatives.browserdoesVideo'">
                            </video>`;
                    return templateVideo
                }
                return "";
            },
            columns() {
                return this.$t('pro.admin.Pendcolumns')
            }
        },
        methods: {
            //显示广告的预览情况1
            PreviewModel(record) {
                this.spinning = true;
                this.visiblePreview = true;
                let parameter = "/" + record.campaignsCreativeId;
                let userId
                if (this.$store.getters.userId !== record.userId){
                    userId = record.userId
                } else {
                    userId = record.userId
                }
                getCampaignsCreative(parameter,userId).
                then(res =>{
                    if (res.data.code == 200){
                        let obj = res.data.data
                        this.mediaType = obj.creativeType
                        if (this.mediaType == 'banners') {
                            this.bannerPreview = obj.banners

                        }else if (this.mediaType == "bannerVideos"){
                            this.videoPreview = obj.bannerVideos

                        }else if (this.mediaType == 'nativeAd') {
                            this.factory(obj.nativeAd)
                        }
                    }
                }).finally(() => {
                    setTimeout(() => {
                        this.spinning = false
                    },950)
                })
            },
            factory(value) {
                let { assetList } = value || {}
                if (assetList) {
                    let newArr = JSON.parse(assetList);
                    let img1 = newArr[1].img;
                    let img2 = newArr[2].img;
                    this.nativePreview = {
                        isShow: true,
                        title: value.assetTitle,
                        dataDesc: value.assetDataDesc,
                        clickUrl: value.clickUrl,
                        sponsor: value.assetDataSponsored,
                        minImgSrc: img1.type === 1 ? img1.url : img2.url,
                        amxImgSrc: img2.type === 3 ? img2.url : img1.url
                    }
                    this.nativeHtml();
                    this.isDisp = true;
                }
            },
            nativeHtml() {
                if (!this.nativePreview)return false;
                let html = `<div class="native-box dark-b-fff">
                                       <a href="${this.nativePreview.clickUrl}" target="_blank">
                                         <img width="100%" src="${this.nativePreview.amxImgSrc}">
                                       </a>
                                       <div class="box-title dark-font-666">
                                           ${this.nativePreview.title}
                                       </div>
                                       <div class="box-content dark-font-777">
                                           <div class="thumb display-block">
                                             <a href="${this.nativePreview.clickUrl}" target="_blank">
                                               <img src="${this.nativePreview.minImgSrc}">
                                             </a>
                                           </div>
                                           <div class="description display-block" style="margin-top: 4px;"><span>${this.nativePreview.dataDesc}</span></div>
                                       </div>
                                       <div class="sponsor display-block dark-font-666">
                                           <span>
                                               ${this.nativePreview.sponsor}
                                           </span>
                                       </div>
                                   </div>`;
                return html;
            },
            handlePreviewClose() {
                this.visiblePreview = false
            },
            handlePreviewNo() {
                this.mediaType = false;
                this.visiblePreview = false
            },
            tipsTo(usId) {
                if (usId != this.$store.getters.userId) {
                    this.$message.info(this.$t('pro.admin.toRex'));
                }
            },
            //跳转广告活动
            editcreative2(record) {
                this.tipsTo(record.userId);
                this.$store.commit("changeUserId", record.userId);
                this.$router.push("/bidder/editcampaign/id/" + record.campaignId);
                this.reload()
            },
            //跳转到对应的广告系列编辑页
            editcreative(record) {
                record.id = record.campaignId;
                record.name = record.campaignsName;
               
                this.tipsTo(record.userId);
                this.$store.commit("changeUserId", record.userId);
                this.$store.commit("changeCampaigns", record);
                this.$router.push("/bidder/editcreative/creativeid/" + record.campaignsCreativeId);
                this.reload()
            },
            //改变页数的事件
            handleChange(page, pageSize) {
                this.pagination.size = pageSize;
                this.pagination.current = page;
                this.fetch()
            },
            fetch(params = {}) {
                this.loading = !this.loading;
                params.page = this.pagination.current || 1;
                params.results = this.pagination.size || 10;
                params.detailedState = MODERATED,
                    getDetailedDataByPage({...params})
                        .then(res => {
                            let data = res.data.data;
                            this.data = data.records;
                            if (this.data.length == 0) {
                                this.empty = true
                            } else {
                                this.data = this.data.map(item => {
                                    item.updatedAt = parseTime(item.updatedAt);
                                    return item
                                });
                                this.pagination = data
                                if (this.pagination.total !== null && this.pagination.total !== 0) {
                                    this.pageSizeOptions = ['10', '20', '30', '40', '50']
                                }
                            }
                        }).finally(() => {
                            this.loading = false;
                        });
            },
            //审核的函数
            handleState(text, detailedState) {
                setDetailedState({
                    detailed: detailedState,
                    id: text.campaignsCreativeId
                }).then(res => {
                    if (res.data.code == 200) {
                        detailedState == NOTACTIVE ?
                            this.$message.success(this.$t('pro.admin.ApprovalSuccess')) :
                            this.$message.error(this.$t('pro.admin.ApprovalError'))
                    }
                    this.fetch()
                }).catch(() => {
                    this.$message.error(this.$t('pro.admin.ApprovalFailure'))
                })
            }
        },
        mounted() {
            this.fetch();

            setTimeout(() => {
                this.initInning = false
            }, 650)
        },
    }
</script>
<style lang="less" scoped>
    .tools {
        padding-top: 30px;
    }

    td {
        display: flex;
    }
</style>

